
// 岗位类型映射表
const scenarioLabels = {
    'ai-engineer': '人工智能工程师',
    'big-data-analyst': '大数据分析师',
    'iot-specialist': '物联网专家',
    'product-manager': '产品经理'
};

// 全局变量
let isPaused = false; // 是否处于暂停状态
const ratingLabels = ['知识专业水平', '技能匹配度', '语言表达能力', '逻辑思维能力', '创新能力', '应变抗压能力'];
let currentScores = [8, 7, 9, 6, 5, 7]; // 示例数据
let allowAnalysisAccess = false;
let mediaRecorder, recordedChunks = [], startTime = null, timerInterval = null;
let currentScenario = '', currentQuestionIndex = 0;
let scoreInterval, radarChartInstance = null;
let pauseBtn = null; // 对暂停/继续按钮的引用

// 题库
const interviewQuestions = {
    "ai-engineer": [
        "请解释深度学习与传统机器学习的区别",
        "如何处理训练数据中的类别不平衡问题",
        "请描述反向传播算法的工作原理"
    ],
    "big-data-analyst": [
        "请说明Hadoop和Spark的核心区别",
        "如何设计实时数据处理流水线",
        "请解释Lambda架构的优缺点"
    ],
    "iot-specialist": [
        "物联网系统中MQTT协议的优势是什么",
        "如何保障智能设备的数据安全",
        "请说明边缘计算与云计算的协同方式"
    ],
    "product-manager": [
        "如何制定产品的MVP方案",
        "请描述用户画像的构建方法",
        "如何处理产品迭代中的需求变更"
    ]
};

function showSection(sectionId) {
    if (!allowAnalysisAccess && sectionId === 'analysis-results') {
        alert('请先完成录制再查看分析结果');
        return;
    }
    document.querySelectorAll('.section').forEach(section => {
        section.style.display = 'none';
    });
    document.getElementById(sectionId).style.display = 'block';
}

// 计时器
function startTimer(resumeFrom = 0) {
    if (timerInterval) {
        clearInterval(timerInterval);
    }
    
    // 记录开始时间点
    recordingStatus.startTime = new Date().getTime() - resumeFrom;
    recordingStatus.elapsedTime = resumeFrom;
    
    timerInterval = setInterval(() => {
        const elapsed = Math.floor((new Date().getTime() - recordingStatus.startTime) / 1000);
        recordingStatus.elapsedTime = elapsed;
        
        const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
        const seconds = (elapsed % 60).toString().padStart(2, '0');
        
        const timerElement = document.getElementById('recording-timer');
        if (timerElement) {
            timerElement.textContent = `${minutes}:${seconds}`;
        }
    }, 1000);
}

function stopTimer() {
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
}

// 摄像头与录制
async function initializeCamera() {
    try {
        const video = document.getElementById('video-preview');
        const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
        video.srcObject = stream;
        
        // 创建MediaRecorder并配置参数
        mediaRecorder = new MediaRecorder(stream, {
            mimeType: 'video/webm; codecs=vp9'
        });
        
        console.log('MediaRecorder初始化成功:', {
            mimeType: mediaRecorder.mimeType,
            state: mediaRecorder.state,
            streamActive: stream.active,
            supportedMimeType: MediaRecorder.isTypeSupported(mediaRecorder.mimeType)
        });
        
        // 验证浏览器是否支持指定的MIME类型
        if (!MediaRecorder.isTypeSupported(mediaRecorder.mimeType)) {
            throw new Error(`不支持的MIME类型: ${mediaRecorder.mimeType}`);
        }
        
        // 初始化数据存储
        recordedChunks = [];
        console.log('已初始化视频数据存储数组');
        
        // 配置数据可用事件处理
        mediaRecorder.ondataavailable = (event) => {
            if (event.data.size > 0) {
                console.log('收到视频数据块:', {
                    size: event.data.size,
                    type: event.data.type,
                    timestamp: Date.now(),
                    currentTime: mediaRecorder.currentTime
                });
                recordedChunks.push(event.data);
            }
        };
        
        // 配置录制结束处理
        mediaRecorder.onstop = () => {
            console.log('录制结束:', {
                totalChunks: recordedChunks.length,
                totalSize: recordedChunks.reduce((acc, chunk) => acc + chunk.size, 0),
                streamActive: stream.active,
                finalState: mediaRecorder.state
            });
            
            const blob = new Blob(recordedChunks, { type: mediaRecorder.mimeType });
            const url = URL.createObjectURL(blob);
            
            // 更新UI状态
            recordingStatus.isRecording = false;
            document.getElementById('recording-status').textContent = '';
            
            // 清理资源
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
            video.srcObject = null;
        };
        
        // 错误处理
        mediaRecorder.onerror = (error) => {
            console.error('MediaRecorder错误:', {
                error: error,
                errorMessage: error.message,
                currentState: mediaRecorder.state
            });
            
            handleRecordingError(`视频录制出错: ${error.message}`);
        };
        
        // 更新录制按钮状态
        document.querySelectorAll('.recording').forEach(btn => btn.disabled = false);
        
    } catch (err) {
        console.error('无法访问摄像头:', {
            error: err,
            message: err.message,
            name: err.name
        });
        
        alert(`无法启动摄像头：${err.message}\n请检查设备权限和浏览器设置`);
        document.getElementById('recording-status').textContent = '摄像头访问失败';
    }
}

function handleRecordingError(message) {
    console.error('录制错误处理:', {
        message: message,
        timestamp: Date.now(),
        mediaRecorderExists: !!mediaRecorder,
        currentState: mediaRecorder?.state
    });
    
    alert(message);
    
    // 重置录制状态
    recordingStatus.isRecording = false;
    recordingStatus.startTime = null;
    recordingStatus.elapsedTime = 0;
    
    // 停止评分
    if (scoreInterval) {
        clearInterval(scoreInterval);
        scoreInterval = null;
    }
    
    // 停止媒体流
    const video = document.getElementById('video-preview');
    const stream = video.srcObject;
    if (stream) {
        const tracks = stream.getTracks();
        tracks.forEach(track => track.stop());
    }
    video.srcObject = null;
    
    // 更新UI状态
    document.getElementById('recording-status').textContent = '录制已终止';
    document.querySelectorAll('.recording').forEach(btn => btn.disabled = true);
    document.querySelectorAll('.paused').forEach(btn => btn.disabled = true);
}

// 新增录制状态变量（原recordingState精简版）
const recordingStatus = {
    isRecording: false,
    startTime: null,
    elapsedTime: 0
};

function startRecording() {
    if (!mediaRecorder || mediaRecorder.state !== 'inactive') {
        console.warn('MediaRecorder未初始化或状态异常:', {
            initialized: !!mediaRecorder,
            currentState: mediaRecorder?.state,
            timestamp: Date.now()
        });
        return;
    }
    
    try {
        // 重置录制数据
        recordedChunks = [];
        console.log('已重置recordedChunks', {
            initialLength: recordedChunks.length,
            timestamp: Date.now()
        });
        
        // 开始录制，设置时间片为1000ms以定期获取数据
        mediaRecorder.start(1000);
        recordingStatus.isRecording = true;
        recordingStatus.startTime = new Date().getTime();
        recordingStatus.elapsedTime = 0;
        
        console.log('MediaRecorder启动:', {
            state: mediaRecorder.state,
            startTime: new Date(recordingStatus.startTime).toLocaleTimeString(),
            currentTime: Date.now(),
            usingTimeSlice: mediaRecorder.stream ? '是' : '否'
        });
        
        startTimer();
        startRealTimeScoring();
        
        // 更新UI状态
        document.getElementById('recording-status').textContent = '录制中...';
        document.querySelectorAll('.recording').forEach(btn => btn.disabled = false);
        document.querySelectorAll('.paused').forEach(btn => btn.disabled = false);
        
    } catch (error) {
        console.error('启动录制失败:', {
            error: error,
            message: error.message,
            timestamp: Date.now(),
            currentState: mediaRecorder?.state
        });
        
        alert('录制启动失败，请检查摄像头权限并重试');
        handleRecordingError(`启动录制失败: ${error.message}`);
    }
}

// 删除了暂停/继续功能相关代码

function stopRecording() {
    if (!mediaRecorder || !['recording', 'paused'].includes(mediaRecorder.state)) {
        alert('请先开始录制视频');
        return;
    }
    
    try {
        console.log('停止录制流程开始:', {
            currentState: mediaRecorder.state,
            chunkCount: recordedChunks.length,
            streamActive: document.getElementById('video-preview').srcObject?.active
        });
        
        mediaRecorder.stop();
        stopTimer();
        
        // 显式检查recordedChunks
        if (recordedChunks.length === 0) {
            console.warn('警告：未收集到视频数据块', {
                state: mediaRecorder.state,
                streamActive: document.getElementById('video-preview').srcObject?.active,
                timestamp: Date.now()
            });
            
            alert('没有可上传的视频数据，请确保正确录制了视频内容');
            document.getElementById('recording-status').textContent = '无视频数据';
            return;
        }
        
        // 计算总大小用于验证
        const totalSize = recordedChunks.reduce((acc, chunk) => acc + chunk.size, 0);
        if (totalSize < 1024) { // 小于1KB视为无效数据
            console.warn('检测到异常小的视频文件:', { size: totalSize + ' bytes' });
            alert('录制的视频文件太小，可能不包含有效内容');
            document.getElementById('recording-status').textContent = '无效视频数据';
            return;
        }
        
        // 重置状态前保存引用
        const chunksToUpload = [...recordedChunks];
        const mimeType = mediaRecorder.mimeType;
        
        // 重置状态
        recordingStatus.isRecording = false;
        recordingStatus.startTime = null;
        recordingStatus.elapsedTime = 0;
        
        if (scoreInterval) {
            clearInterval(scoreInterval);
            scoreInterval = null;
        }
        
        // 清理媒体资源
        const video = document.getElementById('video-preview');
        const stream = video.srcObject;
        if (stream) {
            const tracks = stream.getTracks();
            tracks.forEach(track => track.stop());
        }
        video.srcObject = null;
        
        // 上传视频
        uploadVideoToBackend(chunksToUpload, mimeType);
        
    } catch (error) {
        console.error('停止录制失败:', error);
        alert(`停止录制时发生错误：${error.message}`);
    }
}

// 简历校验
function validateResumeFile(input) {
    const file = input.files[0];
    const errorDiv = document.getElementById('resume-error');
    const allowedTypes = ['application/pdf', 'text/pdf'];
    const maxSize = 10 * 1024 * 1024;
    errorDiv.style.display = 'none';
    input.setCustomValidity('');
    if (!file) return true;
    if (!allowedTypes.includes(file.type)) {
        errorDiv.textContent = '仅支持 PDF 格式的简历文件';
        errorDiv.style.display = 'block';
        input.setCustomValidity('仅支持 PDF 文件');
        return false;
    }
    if (file.size > maxSize) {
        errorDiv.textContent = '文件大小不能超过 10MB';
        errorDiv.style.display = 'block';
        input.setCustomValidity('文件过大');
        return false;
    }
    return true;
}

// 面试题目生成与切换
function generateInterviewQuestion(scenario) {
    if (!interviewQuestions.hasOwnProperty(scenario)) {
        console.error('无效的岗位类型:', scenario);
        return false;
    }
    currentScenario = scenario;
    currentQuestionIndex = 0;
    const questionElement = document.getElementById('current-question');
    const questionNumberElement = document.getElementById('question-number');
    if (questionElement && questionNumberElement) {
        questionElement.textContent = interviewQuestions[scenario][0];
        questionNumberElement.textContent = 1;
        return true;
    }
    return false;
}
function changeQuestion(direction) {
    const questions = interviewQuestions[currentScenario];
    if (!questions) return;
    currentQuestionIndex += direction;
    if (currentQuestionIndex < 0) currentQuestionIndex = 0;
    if (currentQuestionIndex >= questions.length) currentQuestionIndex = questions.length - 1;
    document.getElementById('current-question').textContent = questions[currentQuestionIndex];
    document.getElementById('question-number').textContent = currentQuestionIndex + 1;
}
function prevQuestion() { changeQuestion(-1); }
function nextQuestion() { changeQuestion(1); }

// 简历文本生成
function generateResume() {
    const scenarioLabel = scenarioLabels[currentScenario] || currentScenario;
    const feedbackText = `
智鉴 AI 面试助手 - 简历生成
姓名：[请填写姓名]
应聘岗位：${scenarioLabel}
技能匹配度：★★★☆☆
语言表达能力：★★★★☆
创新能力：★★★☆☆
其他特长：
- 良好的沟通技巧
- 快速学习能力强
- 团队协作经验丰富

根据面试表现，我们建议您加强基础知识理解和表达逻辑性。
`;
    const blob = new Blob([feedbackText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${scenarioLabel}_简历.txt`;
    a.click();
    URL.revokeObjectURL(url);
}

// AI实时打分模拟
function startRealTimeScoring() {
    scoreInterval = setInterval(() => {
        for (let i = 0; i < currentScores.length; i++) {
            const change = Math.floor(Math.random() * 3) - 1;
            currentScores[i] = Math.min(10, Math.max(0, currentScores[i] + change));
        }
    }, 5000);
}
function calculateAverageScores(scoresArray) {
    const avg = scoresArray.reduce((acc, val) => acc + val, 0) / scoresArray.length;
    return new Array(scoresArray.length).fill(avg);
}

// 雷达图
function updateRadarChart() {
    if (!radarChartInstance) return;
    const averageScores = calculateAverageScores(currentScores);
    radarChartInstance.data.datasets[0].data = averageScores;
    radarChartInstance.update();
    document.getElementById('feedback-text').innerText = `
知识专业水平: ${averageScores[0]}/10
技能匹配度: ${averageScores[1]}/10
语言表达能力: ${averageScores[2]}/10
逻辑思维能力: ${averageScores[3]}/10
创新能力: ${averageScores[4]}/10
应变抗压能力: ${averageScores[5]}/10
`;
}
function initRadarChart() {
    const ctx = document.getElementById('radar-chart').getContext('2d');
    radarChartInstance = new Chart(ctx, {
        type: 'radar',
        data: {
            labels: ratingLabels,
            datasets: [{
                label: '平均评分',
                backgroundColor: 'rgba(76, 175, 80, 0.2)',
                borderColor: 'rgba(76, 175, 80, 1)',
                pointBackgroundColor: 'rgba(76, 175, 80, 1)',
                data: calculateAverageScores(currentScores)
            }]
        },
        options: {
            scale: {
                ticks: {
                    beginAtZero: true,
                    max: 10
                }
            }
        }
    });
}

// 面试开始主流程
function startInterview() {
    const scenarioSelect = document.getElementById('job-scenario');
    const resumeInput = document.getElementById('resume-upload');
    const scenario = scenarioSelect.value;
    if (!scenario) { alert('请选择一个面试场景'); return; }
    if (!['ai-engineer', 'big-data-analyst', 'iot-specialist', 'product-manager'].includes(scenario)) {
        alert('请选择有效的面试岗位');
        return;
    }
    if (!resumeInput.files.length) { alert('请上传您的简历文件'); return; }
    if (!validateResumeFile(resumeInput)) return;
    if (!generateInterviewQuestion(scenario)) {
        alert('无法加载题目，请检查选择的岗位');
        return;
    }
    showSection('mock-interview');
    document.getElementById('video-recording').style.display = 'block';
    initializeCamera();
    
    // 开始录制时隐藏 '选择面试场景' 部分
    const jobSelectionCard = document.getElementById('job-selection-card');
    if (jobSelectionCard) {
        jobSelectionCard.style.display = 'none';
    }
    
    if (radarChartInstance) {
        radarChartInstance.data.datasets[0].data = calculateAverageScores(currentScores);
        radarChartInstance.update();
    } else {
        initRadarChart();
    }
    document.getElementById('improvement-tips').innerHTML = `
<strong>改进建议：</strong><br/>
- 加强基础知识的理解与应用<br/>
- 提高表达清晰度和逻辑性<br/>
- 多进行压力测试训练以增强应变能力
`;

    console.log('初始化录制按钮状态');
    // 重置录制按钮状态
    document.getElementById('pause-btn').style.display = 'none'; // 隐藏暂停按钮（不再需要）
    document.getElementById('resume-btn').style.display = 'none'; // 隐藏继续按钮（不再需要）
    
    // 重置其他相关界面元素状态
    document.querySelectorAll('.recording').forEach(btn => btn.disabled = false);
    document.querySelectorAll('.paused').forEach(btn => btn.disabled = true);

}

// AI对话部分
function getAIResponse(userMessage) {
    const responses = {
        "你好": "您好！我是智鉴 AI 面试助手，有什么可以帮助您的？",
        "面试技巧": "面试时注意表达清晰、逻辑严谨，回答要结合实际经验。",
        "如何准备简历": "建议突出项目经验和技能匹配度，保持简洁明了。",
        "自我介绍": "请从学习经历、项目经验、职业规划等方面简要介绍自己。",
        "default": "这是个好问题，我会继续学习并提供更完善的建议。"
    };
    return responses[userMessage.toLowerCase()] || responses.default;
}
function sendMessage() {
    const input = document.getElementById('chat-input');
    const message = input.value.trim();
    if (!message) return;
    addMessage(message, 'user');
    input.value = '';
    setTimeout(() => {
        const response = getAIResponse(message);
        addMessage(response, 'ai');
    }, 800);
}
function addMessage(text, sender) {
    const container = document.getElementById('chat-container');
    const msgDiv = document.createElement('div');
    msgDiv.classList.add('message', sender === 'user' ? 'user-message' : 'ai-message');
    msgDiv.textContent = text;
    container.appendChild(msgDiv);
    container.scrollTop = container.scrollHeight;
}


// 修改后的uploadVideoToBackend函数（添加详细调试信息）
function uploadVideoToBackend(chunks, mimeType) {
    try {
        // 创建Blob对象前验证
        if (!Array.isArray(chunks) || chunks.length === 0) {
            throw new Error('无效的视频数据块数组');
        }
        
        // 创建Blob对象
        const videoBlob = new Blob(chunks, { type: mimeType });
        
        // 验证Blob
        if (!videoBlob || videoBlob.size <= 0) {
            throw new Error('创建的视频Blob无效或大小为0');
        }
        
        console.log('准备上传视频:', {
            blobType: videoBlob.type,
            blobSize: videoBlob.size + ' bytes',
            mimeType: mimeType,
            chunkCount: chunks.length,
            timestamp: Date.now()
        });
        
        // 创建FormData对象
        const formData = new FormData();
        
        // 添加视频文件
        formData.append('video', videoBlob, `interview_video_${Date.now()}.webm`);
        
        // 添加其他元数据
        formData.append('scenario', currentScenario || 'unknown');
        formData.append('timestamp', new Date().toISOString());
        formData.append('size', videoBlob.size);
        formData.append('mimeType', mimeType);
        
        // 显示上传状态
        document.getElementById('recording-status').textContent = '正在上传视频...';
        
        // 模拟上传过程（开发阶段使用）
        /*
        setTimeout(() => {
            console.log('模拟上传成功:', {
                status: 'success',
                videoUrl: URL.createObjectURL(videoBlob),
                size: videoBlob.size,
                type: videoBlob.type
            });
            
            document.getElementById('recording-status').textContent = '视频上传成功';
            alert('视频已成功上传到服务器（模拟）');
            
        }, 1500);
        */
        // 实际上传代码（注释掉供生产使用）
    
        fetch('https://your-backend-api.com/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('上传成功:', data);
            document.getElementById('recording-status').textContent = '视频上传成功';
            alert('视频已成功上传到服务器');
        })
        .catch(error => {
            console.error('上传失败:', error);
            document.getElementById('recording-status').textContent = '视频上传失败';
            alert(`视频上传失败：${error.message}`);
        });
        
    } catch (error) {
        console.error('上传处理错误:', error);
        document.getElementById('recording-status').textContent = '视频上传失败';
        alert(`视频上传失败：${error.message}`);
    }
}